package com.yunmaozj.tools.site.server.config;

import com.yunmaozj.tools.site.server.dto.Developer;
import com.yunmaozj.tools.site.server.util.FileManager;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static java.util.Objects.isNull;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;

/**
 * @author zhongminghong
 * @email zhongmh@yunmaozj.com
 * @create 2022-05-26 23:30
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class MvcConfiguration implements WebMvcConfigurer {

    private FileManager fileManager;
    private StringRedisTemplate redisTemplate;
    private ResourceCacheManager resourceCacheManager;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/docs/**")
                .addResourceLocations("classpath:/template/docs/");
        registry.addResourceHandler("/docs/view/**")
                .addResourceLocations(fileManager.getRootDirectory().toURI().toString());

    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ResourcesHandlerInterceptor()).addPathPatterns("/docs/view/**");
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                Cookie cookie = WebUtils.getCookie(request, "JSESSIONID");
                if (isNull(cookie)) {
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    return false;
                }
                String sessionId = "_" + cookie.getValue();
                log.info("[{}]->>>>{}", cookie.getValue(), request.getRequestURI());
                return resourceCacheManager.isLogin(sessionId);
            }
        }).addPathPatterns("/site/uploadFile/**", "/site/uploadMetadata/**");
    }


    /**
     * 资源拦截器
     */
    class ResourcesHandlerInterceptor implements HandlerInterceptor {

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String url = request.getRequestURI();
            Cookie cookie = WebUtils.getCookie(request, "JSESSIONID");
            if (isNull(cookie)) {
                response.setStatus(SC_FORBIDDEN);
                return false;
            }
            String sessionId = cookie.getValue();
            if (!resourceCacheManager.isLogin(sessionId)) {
                response.setStatus(SC_FORBIDDEN);
                return false;
            }
            String username = resourceCacheManager.username(sessionId);
            String[] arrays = url.split("/");
            if (arrays.length < 2) {
                response.setStatus(SC_FORBIDDEN);
                return false;
            }
            //获取项目名称
            String project = arrays[3];
            if (resourceCacheManager.exists(username, project)) {
                return true;
            }

            log.info("拦截用户[{}]对项目[{}]的访问", username, project);
            response.setStatus(SC_FORBIDDEN);
            response.setHeader("Content-Type", "text/html;charset=UTF-8");
            response.getOutputStream().write("<h1>无权访问</h1>".getBytes());
            return false;
        }
    }
}
